<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

  <script type="text/javascript">

    function WebSocketTest()
    {
      if ("WebSocket" in window)
      {

        // 打开一个 web socket
          var name = document.getElementById("name").value;
         ws = new WebSocket("ws://"+location.host+"/websocket/"+name);

        ws.onopen = function()
        {
          // Web Socket 已连接上，使用 send() 方法发送数据
         // ws.send("发送数据");
        //  alert("数据发送中...");
            aaaaaaaa("建立连接")
        };

        ws.onmessage = function (evt)
        {
          var received_msg = evt.data;
         // alert("数据已接收...");
            aaaaaaaa(received_msg)
        };

        ws.onclose = function()
        {
          // 关闭 websocket
          //alert("连接已关闭...");
            aaaaaaaa("关闭连接")
        };
      }

      else
      {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
      }
    }

    function aaaaaaaa(data) {
        var span = document.getElementById("msg");
        span.innerHTML=data;
    }

    function sendMessage() {
        //发送消息
        //首先找到要发给谁
        var touser = document.getElementById("touser").value;
        var content = document.getElementById("content").value;
        var msg={"touser":touser,"msg":content}

        //获取到要送的内容
        //拼接成 json 字符串
        var json = JSON.stringify(msg);
        // 通过 ws 发送消息
        ws.send(json);
    }
  </script>
</head>
<body >

用户名:<input id="name"> <button onclick="WebSocketTest()">连接</button>
<br><br><br><br>

接收方:<input id="touser"><br>
<br><br><br>
聊天内容<textarea cols="50"  id="content"></textarea>
<br><br><br>
<button onclick="sendMessage()">发送</button>
<br><br><br>

<span id="msg"></span>

</body>
</html>